<?php

namespace App\Http\Controllers\Api\AdminCode;

use App\Http\Controllers\Api\AdminCode\Traits\adminRequestUserData;
use App\Http\Controllers\Api\BaseController;
use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxCommentLikeRepositores;
use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Http\Controllers\Api\Repositories\WxLikeRepositores;
use App\Http\Controllers\Api\Repositories\WxSyncRelationRepositories;
use App\Http\Controllers\Api\Repositories\WxTagsRepositories;
use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use Illuminate\Http\Request;

class AdminPostsController extends BaseController
{
    use adminRequestUserData;
    /**
     * 增
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request){

        // 检查用户是否存在
        if(_empty_($request->author) || _empty_($request->author['id']) || _empty_($request->author['nickName'])){
            return $this->fail(1001001, []);
        }

        $uid = WxSyncRelationRepositories::wx_uid($request->domain, $request->author['id']);
        if(_empty_($uid)){
            $data = $this->collectUserData($request);
            $uid = WxUserRepositores::registerUser($data);
            if(!$uid){
                return $this->fail(200002, ['msg'=>'用户数据插入失败']);
            }
        }

        $tag_ids = [];

        if($request->tags_name){
            foreach (explode(',', $request->tags_name) as $tag_name){
                try{
                    $tag_ids[] = WxTagsRepositories::add($uid, $tag_name)->id;
                }catch (\Exception $e){
                    _logger_(__file__, __line__, $e->getMessage());
                }
            }
        }
        $good_ids = [];

        $r = PostsRepositores::admin_add($request->domain, $uid, '',$request->contents, $request->circle_id, $tag_ids, $good_ids, $request->image_url, $request->video_url, $request->address_id, $request->id, $request->date);
        if($r){
            $c = [];
            if($request->comments){
                $c = self::processComments($request->domain, $request->comments);
            }
            $l = [];
            if($request->likes){
                $l = $this->likes($request->domain, $request->likes, $request->id,true);
            }
            return $this->success(['msg'=>'ok', 'comment'=>$c, 'likes'=>$l]);
        }else{
            return $this->fail(200002, ['msg'=>'文章数据插入失败']);
        }
    }

    private function processComments($domain, $comments){
        if(_empty_($comments)){
            return [];
        }
        // 循环两次
        // 第一次父评论
        $fathers = [];
        foreach ($comments as $comment){
            if($comment['comment_id'] == 0){

                if(_empty_($comment['author']) || _empty_($comment['author']['id']) || _empty_($comment['author']['nickName'])){
                    continue;
                }

                // 文章
                $postId = WxSyncRelationRepositories::wx_post_id($domain, $comment['posts_id']);
                if(!$postId){
                    continue;
                }

                // 评论作者
                $uid = WxSyncRelationRepositories::wx_uid($domain, $comment['author']['id']);
                if(_empty_($uid)){
                    $user_data = [];
                    $user_data['domain'] = $domain;
                    $user_data['mp_openId'] = $comment['author']['mp_openId'] ?? '';
                    $user_data['web_openId'] = $comment['author']['web_openId'] ?? '';
                    $user_data['app_openId'] = $comment['author']['app_openId'] ?? '';
                    $user_data['unionId'] = $comment['author']['unionId'] ?: '';
                    $user_data['nickName'] = $comment['author']['nickName'];
                    $user_data['user_background_maps'] = $comment['author']['user_background_maps'] ?: '';
                    $user_data['avatarUrl'] = $comment['author']['avatarUrl'] ?: '';
                    $user_data['gender'] = $comment['author']['gender'] ?: 0;
                    $user_data['external_id'] = $comment['author']['id'];
                    $user_data['date'] = $comment['author']['date'];
                    $uid = WxUserRepositores::registerUser($user_data);
                    if(!$uid){
                        continue;
                    }
                }

                // 父级评论
                $parent_comment_id = null;
                $comment_agent_id = null;

                // id
                // $posts_id, $comment_id, $reply_user_id, $user_id, $comment_content, $comment_img_url
                $r = WxCommentRepositores::admin_add($domain, $postId, $parent_comment_id, $comment_agent_id, $uid, $comment['comment_content'], $comment['comment_img_url'], $comment['id'], $comment['date']);
                if($r){
                    if(isset($comment['likes']) && $comment['likes']){
                        $this->likes($domain, $comment['likes'],  $comment['id'], false);
                    }
                    $fathers[] = $comment['id'];
                }
            }
        }

        foreach ($comments as $comment){
            if( in_array($comment['comment_id'], $fathers) ){

                if(_empty_($comment['author']) || _empty_($comment['author']['id']) || _empty_($comment['author']['nickName'])){
                    continue;
                }

                // 文章
                $postId = WxSyncRelationRepositories::wx_post_id($domain, $comment['posts_id']);
                if(!$postId){
                    continue;
                }

                // 评论作者
                $uid = WxSyncRelationRepositories::wx_uid($domain, $comment['author']['id']);
                if(_empty_($uid)){
                    $user_data = [];
                    $user_data['domain'] = $domain;
                    $user_data['mp_openId'] = $comment['author']['mp_openId'] ?? '';
                    $user_data['web_openId'] = $comment['author']['web_openId'] ?? '';
                    $user_data['app_openId'] = $comment['author']['app_openId'] ?? '';
                    $user_data['unionId'] = $comment['author']['unionId'] ?: '';
                    $user_data['nickName'] = $comment['author']['nickName'];
                    $user_data['user_background_maps'] = $comment['author']['user_background_maps'] ?: '';
                    $user_data['avatarUrl'] = $comment['author']['avatarUrl'] ?: '';
                    $user_data['gender'] = $comment['author']['gender'] ?: 0;
                    $user_data['external_id'] = $comment['author']['id'];
                    $user_data['date'] = $comment['author']['date'];
                    $uid = WxUserRepositores::registerUser($user_data);
                    if(!$uid){
                        continue;
                    }
                }

                // 父级评论
                $parent_comment_id = null;
                $comment_agent_id = null;
                if($comment['comment_id'] > 0){
                    $inner_id = WxSyncRelationRepositories::wx_comment_id($domain, $comment['comment_id']);
                    $parent_comment = WxComment::find($inner_id);
                    if($parent_comment){
                        $parent_comment_id = $parent_comment->id;
                        $comment_agent_id = $parent_comment->user_id;
                    }else{
                        continue;
                    }
                }
                // id
                // $posts_id, $comment_id, $reply_user_id, $user_id, $comment_content, $comment_img_url
                $r = WxCommentRepositores::admin_add($domain, $postId, $parent_comment_id, $comment_agent_id, $uid, $comment['comment_content'], $comment['comment_img_url'], $comment['id'], $comment['date']);
                if($r){
                    if(isset($comment['likes']) && $comment['likes']){
                        $this->likes($domain, $comment['likes'], $comment['id'], false);
                    }
                    $fathers[] = $comment['id'];
                }
            }
        }


        return $fathers;
    }

    public function likes($domain, $users, $object,  $is_post = false){
        if(_empty_($users)){
            return [];
        }
        $uids = [];
        foreach ($users as $user){

            $user_data = [];
            $user_data['domain'] = $domain;
            $user_data['mp_openId'] = $user['mp_openId'] ?? '';
            $user_data['web_openId'] = $user['web_openId'] ?? '';
            $user_data['app_openId'] = $user['app_openId'] ?? '';
            $user_data['unionId'] = $user['unionId'] ?: '';
            $user_data['nickName'] = $user['nickName'];
            $user_data['user_background_maps'] = $user['user_background_maps'] ?: '';
            $user_data['avatarUrl'] = $user['avatarUrl'] ?: '';
            $user_data['gender'] = $user['gender'] ?: 0;
            $user_data['external_id'] = $user['id'];
            $user_data['date'] = $user['date'];
            $uid = WxUserRepositores::registerUser($user_data);
            if(!$uid){
                continue;
            }
            $uids[] = $uid;
        }

        $rs = [];
        if($is_post){

            foreach ($uids as $uid){
                $postId = WxSyncRelationRepositories::wx_post_id($domain, $object);
                if($postId){
                    $r = WxLikeRepositores::admin_like($uid, $postId);
                    $rs[] = $r;
                }
            }

        }else{
            foreach ($uids as $uid){
                $commentId = WxSyncRelationRepositories::wx_comment_id($domain, $object);
                if($commentId) {
                    $r = WxCommentLikeRepositores::like($uid, $commentId);
                    $rs[] = $r;
                }
            }

        }

        return $rs;
    }


    /**
     * 删
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request){
       $inner_id = WxSyncRelationRepositories::wx_post_id($request->domain, $request->id);
       if(!$inner_id){
           return $this->fail(200003, ['msg'=>'没有对应的文章']);
       }
       if( WxPost::where('id', $inner_id)->delete() ){
           return $this->success(['msg'=>'ok']);
       }else{
           return $this->fail(200002, ['msg'=>'数据库删除失败']);
       }
    }

    /**
     * 改
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request){

    }

}
